package cn.cuilan.common.pipeline;

import cn.cuilan.common.entity.EchoMessage;
import cn.cuilan.common.entity.ProtocolMessage;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;

/**
 * 闲置事件处理器
 *
 * @author zhang.yan
 */
@Slf4j
public class IdleEventHandler extends ChannelHandlerAdapter {

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent e = (IdleStateEvent) evt;
            // 读闲置或全部闲置
            if (e.state() == IdleState.READER_IDLE || e.state() == IdleState.ALL_IDLE) {
                final ProtocolMessage echoMessage = createEchoMessage();
                echoMessage.pack();
                ctx.write(echoMessage);
                ctx.flush();
            }
        }
    }

    public ProtocolMessage createEchoMessage() {
        log.info("Echo server.");
        return new EchoMessage(EchoMessage.PING);
    }
}
